import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

class ImageListView extends StatelessWidget {
  final List<String> images;
  final bool isLoadingNext;
  final ItemScrollController itemScrollController;
  final ScrollOffsetController scrollOffsetController;
  final ItemPositionsListener itemPositionsListener;
  final Future<void> Function() onRefresh;

  const ImageListView({
    super.key,
    required this.images,
    required this.isLoadingNext,
    required this.itemScrollController,
    required this.scrollOffsetController,
    required this.itemPositionsListener,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    if (images.isEmpty) {
      return const Center(
        child: Text(
          '本章没有图片',
          style: TextStyle(color: Colors.white),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: onRefresh,
      color: const Color(0xFF8A2BE2),
      backgroundColor: Colors.black87,
      child: ScrollablePositionedList.builder(
        itemCount: images.length + (isLoadingNext ? 1 : 0),
        itemBuilder: (context, index) {
          // 底部加载指示器
          if (index >= images.length) {
            return const Padding(
              padding: EdgeInsets.all(20.0),
              child: Center(
                child: Column(
                  children: [
                    CircularProgressIndicator(color: Colors.white),
                    SizedBox(height: 8),
                    Text(
                      '加载下一章...',
                      style: TextStyle(color: Colors.white, fontSize: 12),
                    ),
                  ],
                ),
              ),
            );
          }
          // 显示图片
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 2.0),
            child: CachedNetworkImage(
              imageUrl: images[index],
              fit: BoxFit.fitWidth,
              progressIndicatorBuilder: (context, url, progress) => Center(
                child: CircularProgressIndicator(
                  value: progress.progress,
                ),
              ),
            ),
          );
        },
        itemScrollController: itemScrollController,
        scrollOffsetController: scrollOffsetController,
        itemPositionsListener: itemPositionsListener,
        physics: const AlwaysScrollableScrollPhysics(),
      ),
    );
  }
}
